package com.qianke.common;

import com.qianke.common.exception.BizException;
import com.qianke.domain.Constants;
import com.qianke.domain.dto.LoginUserDto;
import com.qianke.domain.entity.BaseEntity;
import org.apache.commons.lang3.StringUtils;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class CommonUtils {
    public static String getWeekStringByWeekNum(int week) {
        switch (week) {
            case 1:
                return "周一";
            case 2:
                return "周二";
            case 3:
                return "周三";
            case 4:
                return "周四";
            case 5:
                return "周五";
            case 6:
                return "周六";
            case 7:
                return "周日";
            default:
                return "";
        }
    }

    //将当天的时间秒转换为时间字符串
    public static String convertTime(int time) {
        int hour = time / 3600;
        String hourStr = String.valueOf(hour);
        if (hour < 10) {
            hourStr = "0" + hour;
        }
        int minute = (time % 3600) / 60;
        String minuteStr = String.valueOf(minute);
        if (minute < 10) {
            minuteStr = "0" + minute;
        }
        return hourStr + ":" + minuteStr;
    }

    public static void insert(BaseEntity baseEntity, Integer operatorId, String operatorName) {
        baseEntity.setCreatorId(operatorId);
        baseEntity.setCreatorName(operatorName);
        baseEntity.setCreateTime(new Date());
        baseEntity.setModifierId(operatorId);
        baseEntity.setModifierName(operatorName);
        baseEntity.setModifiedTime(new Date());
    }

    public static void modify(BaseEntity baseEntity, Integer operatorId, String operatorName) {
        baseEntity.setModifierId(operatorId);
        baseEntity.setModifierName(operatorName);
        baseEntity.setModifiedTime(new Date());
    }

    public static void insert(BaseEntity baseEntity, LoginUserDto loginUserDto) {
        if (loginUserDto == null) {
            insert(baseEntity, Constants.ADMIN_USER_ID, Constants.ADMIN_USER_NAME);
        } else {
            insert(baseEntity, loginUserDto.getId(), loginUserDto.getNickname());
        }
    }

    public static void update(BaseEntity baseEntity, LoginUserDto loginUserDto) {
        if (loginUserDto == null) {
            throw new BizException("获取登录信息失败,请刷新后重试");
        }
        baseEntity.setModifierId(loginUserDto.getId());
        baseEntity.setModifierName(loginUserDto.getNickname());
        baseEntity.setModifiedTime(new Date());
    }

    public static void modify(BaseEntity baseEntity, LoginUserDto loginUserDto) {
        if (loginUserDto == null) {
            modify(baseEntity, Constants.ADMIN_USER_ID, Constants.ADMIN_USER_NAME);
        } else {
            baseEntity.setModifierId(loginUserDto.getId());
            baseEntity.setModifierName(loginUserDto.getNickname());
            baseEntity.setModifiedTime(new Date());
        }

    }

    //根据模板获取实际内容（替换{}）
    public static String getContent(String template, String replaceStr) {
        Assert.assertNotNull(template);
        template.replace("{}", replaceStr);

        return template;
    }

    //根据模板获取实际内容
    public static String getContent(String pattern, Object[] params) {
        MessageFormat messageFormat = new MessageFormat(pattern);
        pattern = messageFormat.format(params);

        return pattern;
    }

    //将集合转化为String
    public static String collectionToString(List list) {
        if (list == null || list.size() <= 0) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        if (list.size() == 1) {
            return sb.append(list.get(0)).toString();
        }
        for (int index = 0; index < list.size(); index++) {
            if (index < list.size() - 1) {
                sb.append(list.get(index));
                sb.append(",");
            } else {
                sb.append(list.get(index));
            }
        }
        return sb.toString();
    }

    /**
     * 将字符串转为集合
     *
     * @param str   目标字符串
     * @param split 间隔字符
     * @return
     */
    public static List StringToList(String str, String split) {
        if (str == null || split == null) {
            return null;
        }
        return Arrays.asList(str.split(split));
    }

//    /**
//     * 根据key从redis的db3中获取值
//     *
//     * @param redisTemplate
//     * @param configKey
//     * @return
//     */
//    public static String getConfigValue(RedisTemplate redisTemplate, String configKey) {
//        RedisTemplate redisTemplateDB = RedisUtils.setConnectionFactoryDB(redisTemplate, 3);
//        ValueOperations<String, String> hashCache = redisTemplateDB.opsForValue();
//        return hashCache.get(configKey);
//    }

//    /**
//     * 根据key更新redis的db3中的值
//     *
//     * @param redisTemplate
//     * @param configKey
//     * @param configValue
//     * @return
//     */
//    public static Boolean updateConfigValueResult(RedisTemplate redisTemplate, String configKey, String configValue) {
//        RedisTemplate redisTemplateDB = RedisUtils.setConnectionFactoryDB(redisTemplate, 3);
//        redisTemplateDB.opsForValue().set(configKey, configValue);
//        return true;
//    }

    ///获取到list集合最后一个元素
    public static <T> T getLast(List<T> list) {
        if (list.size() <= 0) {
            return null;
        }
        return list.get(list.size() - 1);
    }

    /**
     * 将UniCode转为utf-8
     *
     * @param dataStr
     * @return
     */
    public static String decodeUnicode(final String dataStr) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = dataStr.indexOf("\\u", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = dataStr.substring(start + 2, dataStr.length());
            } else {
                charStr = dataStr.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }

    /**
     * 获取小数点后几位
     *
     * @param number      要截取的数字
     * @param accurateNum 精确的位数
     * @return
     */
    public static String getAccurateNumber(String number, int accurateNum) {
        if (StringUtils.isEmpty(number)) {
            throw new BizException("要精确的数字为null");
        }
        if (!number.contains(".")) {
            return "0";
        }
        System.out.println(number);
        int index = number.indexOf('.') + 1;
        return number.substring(index, index + accurateNum);
    }

    //比较时间是否无冲突，无冲突时返回true
    public static boolean isNotConflict(Integer startSecondTime, Integer endSecondTime, Integer startCompareTime, Integer endCompartTime) {
        if (endSecondTime <= startCompareTime || startSecondTime >= endCompartTime) {
            return true;
        }
        return false;
    }
}
